package cn.caipengbo.helloandroid;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Main2Activity extends AppCompatActivity implements View.OnClickListener {

    private EditText editText;
    private Button button1;
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        editText = (EditText) findViewById(R.id.activity2_edit1);
        Intent intent = getIntent();
        String msg = intent.getStringExtra("msg");
        editText.setText(msg);
        button1 = (Button) findViewById(R.id.activity2_button1);
        // 未使用匿名类
        button1.setOnClickListener(this);
        // button2 在配置文件中写onClick事件，绑定方法
        //  android:onClick="onClickButton2"
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(Main2Activity.this, MainActivity.class);
        startActivity(intent);
    }

    // 点击button2 触发的方法
    public void onClickButton2(View view) {
        Intent intent = getIntent();
        String msg = intent.getStringExtra("msg");
        String result = editText.getText().toString() + msg;
        intent.putExtra("result", result);
        setResult(4, intent);
        finish();  // activity 销毁之后会 回调上一个页面的 onActivityResult 方法
    }
    // 按 back 键会执行此函数, 默认是调用 finish(), finish 里面 onDestroy() Activity就会被销毁
    @Override
    public void onBackPressed() {
        Intent intent = getIntent();
        String msg = intent.getStringExtra("msg");
        String result = editText.getText().toString() + msg;
        intent.putExtra("result", result);
        setResult(4, intent);
        finish(); // activity 销毁之后会 回调上一个页面的 onActivityResult 方法
    }
}
